﻿/*
 * Created by SharpDevelop.
 * User: Matjaž
 * Date: 13.12.2008
 * Time: 18:42
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace gopher
{
	/// <summary>
	/// Description of WebViewer.
	/// </summary>
	public partial class WebViewer : Form
	{
		public string mojStreznik;
		public string mojSelektor;
		public string mojaVrata;
		public int mojTimeout;
		public string mojFolder;
		public bool plus = false;
		
		public WebViewer(string selektor, string streznik, string vrata, int iTimeout, string folder)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			mojStreznik = streznik;
			mojSelektor = selektor;
			mojaVrata = vrata;
			mojTimeout = iTimeout;
			mojFolder = folder;
		}
		
		static string ReadLine (Stream s)
		{
			List<byte> lineBuffer = new List<byte>();
			while (true)
			{
				int b = s.ReadByte();
				if (b == 10 || b < 0) break;
				if (b != 13) lineBuffer.Add ((byte)b);
			}
			return Encoding.UTF8.GetString (lineBuffer.ToArray());
			//return Encoding.ASCII.GetString (lineBuffer.ToArray());
		}

		static void SendCommand (Stream stream, string line)
		{
			byte[] data = Encoding.UTF8.GetBytes (line + "\r\n");
			//byte[] data = Encoding.ASCII.GetBytes (line + "\r\n");
			stream.Write (data, 0, data.Length);
		}

		void WebViewerLoad(object sender, EventArgs e)
		{
			if(mojSelektor.Contains("\t+"))
			{
				plus = true;
			}
			Random random = new Random();
			int test = random.Next();
			if((mojSelektor.Length>5) && (mojSelektor.ToLower().Contains("url:")))
			{
				this.webBrowser1.Navigate(mojSelektor.Substring(mojSelektor.IndexOf(":")+1));
				urlBox.Text = mojSelektor.Substring(mojSelektor.IndexOf(":")+1);
			}
			else
			{
				StringBuilder sb = new StringBuilder();
				using (TcpClient client = new TcpClient (mojStreznik, Convert.ToInt32(mojaVrata)))
				using (NetworkStream n = client.GetStream())
				{
					SendCommand (n, mojSelektor);
					string plusLine="";
					List<string> imenik = new List<string>();
					StringBuilder SB = new StringBuilder();
					if (n.DataAvailable == false) Thread.Sleep(mojTimeout);
					TextWriter sw = new StreamWriter(mojFolder+"\\page"+test+".htm");
					int i = 0;
					int j = 0;
					while(imenik.Count == 0)		//
					{								// večkratna ponovitev če večkrat ne dobimo nič...
						j++;
						while (n.DataAvailable)
						{
							string line = ReadLine (n);
							if(i == 0 && plus)
							{
								plusLine = line;
								if(line.StartsWith("+"))
								{
									line = string.Empty;
								}
								i++;
							}
							if((plus == false) && (line == ".")) break;
							if((plus) && (plusLine.StartsWith("+-1")) && (line == ".")) break;
							sw.WriteLine(line);
							imenik.Add(line);
							//SB.Append("\r\n");
							if (n.DataAvailable == false) Thread.Sleep(mojTimeout);
						}
						if((j == 5) || (imenik.Count != 0))					// poskusimo petkrat
						{							// to je za to, da nimamo večkratnik ponovitev
							break;					//
						}							//
						Thread.Sleep(mojTimeout);		//
					}
//					foreach(string vrstica in imenik)
//					{
//						sw.WriteLine(vrstica);
//					}
					
					sw.Flush();
					sw.Close();
					//sw.Write(SB.ToString());
				}
				this.webBrowser1.Navigate(mojFolder+"\\page"+test.ToString()+".htm");

				this.Text = mojSelektor.Substring(mojSelektor.LastIndexOf("\\")+1);
				urlBox.Text = mojSelektor;
			}
		}
		
		void WebViewerHelpRequested(object sender, HelpEventArgs hlpevent)
		{
			Help.ShowHelp(this, Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"))+"\\Help\\gopher.chm", "html\\web-viewer.htm");
		}
	}
}
